import { logout, reqLogin, reqUserInfo } from '@/api/user/user';
import { defineStore } from 'pinia';





const initUserInfo = () => ({
    avatar: '',
    name: '',
})

export const useUserInfoStore = defineStore('userInfo', {


    state: () => ({
        token: localStorage.getItem('token'),
        userInfo: initUserInfo()
    }),
    actions: {
        // 登录
        async login(phone: string, password: string) {
            try {

                let result = await reqLogin({ phone, password })
                console.log(result.data.token);
                localStorage.setItem('token', result.data.token)
                this.token = result.data.token  //给 localStorage 设置的token
                

            } catch (error) {
                console.log(error);

                return Promise.reject(error)
            }
        },
        // 获取个人信息
        async getInfo() {
            try {
                let result = await reqUserInfo()
                console.log(result.data);
                
                this.userInfo = result.data;
            } catch (error) {
                return Promise.reject(error)
            }
        },
        // 退出登录
        async reset() {
            try {
                await logout()
            } catch (error) {
                console.error(error);
            } finally {
                // 删除local中保存的token
                localStorage.removeItem('token')
                // 提交重置用户信息的mutation
                this.userInfo = initUserInfo()
                this.token = ''

            }
        },
    }
})